import re

from bs4 import BeautifulSoup

html = """
<html><head><title>The Dormouse's story</title></head>
<body>
<p class="title" name="dromouse"><b>The Dormouse's story</b></p>
<p class="story">Once upon a time there were three little sisters; and their names were
<a href="http://example.com/elsie" class="sister" id="link1">Elsie</a>,
<a href="http://example.com/lacie" class="sister" id="link2">Lacie</a> and
<a href="http://example.com/tillie" class="sister" id="link3">Tillie</a>;
and they lived at the bottom of a well.</p>
<p class="story">...</p>
"""

# 创建 Beautiful Soup 对象
soup = BeautifulSoup(html, features="lxml")

# 根据名字找标签
b_list = soup.find_all("b")
print(b_list)
# print(type(b_list[0]))

a_list = soup.find_all("a")
print(a_list)

# 根据正则表达式找标签
b_start_list = soup.find_all(re.compile(r"^b"))  # ^匹配开始  $匹配结尾
print(b_start_list)
# 可以提取属性
for tag in b_start_list:
    # print(tag.__dict__)  # 打印所有的属性名
    print(tag.name)

# 根据标签属性找标签
link1_list = soup.find_all(id="link1")
print(link1_list)

# link1_list = soup.find_all(class="story")
# print(link1_list)

class_list = soup.find_all(**{"class": "story"})  # ---> class=story
print(class_list)


# 搜索内容
text_list = soup.find_all(text="Lacie")  # 注意是内容完全匹配
print(text_list)

text_list = soup.find_all(text=re.compile(r"e"))
print(text_list)

# 提取找到的标签对应的属性
print(soup.find_all("a")[0].get("href"))

# 提取找到的标签对应的内容
print(soup.find_all("a")[0].get_text())
